import { asyncRouterMap, constantRouterMap } from '@/router'
import { validateNull } from '@/utils/validate'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, permissions, route) {
  if (!validateNull(route.permission)) {
    console.log('--------permissions----------')
    console.log(permissions)
    console.log('-route.permission-' + route.permission)
    return permissions.includes(route.permission)
    // permissions.forEach(permission => {
    //   if(permission === route.permission){
    //     return true
    //   }
    // });
  } else {
    return true
  }
  // if (route.meta && route.meta.roles) {
  //   return roles.some(role => route.meta.roles.includes(role))
  // } else {
  //   return true
  // }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, roles, permissions) {
  const res = []
  console.log('----------filterAsyncRouter----------')
  console.log(routes)
  routes.forEach(route => {
    console.log('--------11111----------')
    const tmp = { ...route }
    if (hasPermission(roles, permissions, tmp)) {
      if (tmp.children) { // 遍历子菜单
        console.log('--------2222----------')
        tmp.children = filterAsyncRouter(tmp.children, roles, permissions)
        console.log('--------3333----------')
        if (tmp.children.length > 0) { // 有子菜单，必须大于0，才把父菜单显示出来
          res.push(tmp)
        }
      } else { // 没有子菜单
        res.push(tmp)
      }
    }
  })
  console.log('----------res-----------')
  console.log(res)
  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { roles, permissions } = data
        let accessedRouters
        console.log('---------roles--------')
        console.log(roles)
        console.log('---------permissions--------')
        console.log(permissions)

        console.log('---------begin GenerateRoutes filterAsyncRouter--------')

        accessedRouters = filterAsyncRouter(asyncRouterMap, roles, permissions)

        console.log('---------end GenerateRoutes filterAsyncRouter--------')
        console.log(accessedRouters)
        // if (roles.includes('admin')) {
        //   accessedRouters = asyncRouterMap
        // } else {
        //   accessedRouters = filterAsyncRouter(asyncRouterMap, roles, permissions)
        // }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
